package com.nav.games.app.usermgmt;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nav.games.app.busobj.def.User;
import com.nav.games.app.usermgmt.viewdataobj.def.Login;

@Controller
@RequestMapping("/login")
public class LoginAction {
	protected final Log logger = LogFactory.getLog(getClass());
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@Autowired
	private MessageSource messageSource;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String execute(@ModelAttribute(value="login")Login login, HttpServletRequest request, HttpServletResponse response, Locale locale, ModelMap map) throws NoSuchMessageException, Exception {
		Session session = sessionFactory.openSession();
		try {
			User user = (User)session.get(User.class, login.getEmail());
			if(user == null) {
				// Invalid email
				response.setStatus(600);
				map.addAttribute("message", messageSource.getMessage("errormsg.invalidemail", null, locale));
				return "failure-message";
			}
			if(!user.getPassword().equals(login.getPassword())) {
				// Wrong password
				response.setStatus(600);
				map.addAttribute("message", messageSource.getMessage("errormsg.invalidpassword", null, locale));
				return "failure-message";
			}
			request.getSession().setAttribute("user", user);
			return "top";
		} catch(HibernateException e) {
		} finally {
			session.close();
		}
		response.setStatus(600);
		map.addAttribute("message", messageSource.getMessage("errormsg.unknown", null, locale));
		return "failure-message";
	}
}
